package com.yuneec.fly;

import android.app.Application;
import android.util.Log;
import android.widget.Toast;

import com.yuneec.droneservice.ServiceManager;
import com.yuneec.droneservice.protocol.ProtocolPlugin;
import com.yuneec.fly.events.EventBusFactory;
import com.yuneec.fly.events.uiEvent.ShowToastEvent;
import com.yuneec.fly.presenters.DronePresenter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * Created by jw.gu on 2016/6/12.
 */
public class DroneApplication extends Application {
    private static DroneApplication application;

    public static DroneApplication getApplication() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registAOAPlugin();
        application = this;
        DronePresenter.getInstance();
        if (!EventBusFactory.getUiBus().isRegistered(this)) {
            EventBusFactory.getUiBus().register(this);
        }
    }

    public int getHeightPixels() {
        return getResources().getDisplayMetrics().heightPixels;
    }

    private Toast toast;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void showToast(ShowToastEvent event) {
        if (toast == null) {
            toast = Toast.makeText(this, event.msg, event.longTime ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
        } else {
            toast.setText(event.msg);
            toast.setDuration(event.longTime ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
        }
        toast.show();
    }

    public boolean isMavLink = false;

    private final void registAOAPlugin() {
        isMavLink = false;
        Log.d("zzd", "DO regist AOA plugin......");
        Class<ProtocolPlugin> plugin = null;
        try {
            plugin = (Class<ProtocolPlugin>) Class.forName("com.yuneec.mavlink.MavLinkProtocolPlugin");
            isMavLink = true;
        } catch (ClassNotFoundException e) {
            Log.d("zzd", "com.yuneec.mavlink.MavLinkProtocolPlugin not found!");
            try {
                plugin = (Class<ProtocolPlugin>) Class.forName("com.yuneec.rcdronesercive.RCProtocolPlugin");
            } catch (ClassNotFoundException e1) {
                Log.d("zzd", "com.yuneec.rcdronesercive.RCProtocolPlugin not found!");
            }
        }
        if (plugin != null) {
            try {
                ProtocolPlugin plug = plugin.newInstance();
                if (plug != null) {
                    ServiceManager.getInstance().useProtocolPlugin(plug);
                } else {
                    Log.d("zzd", "regist AOA plugin error!!!");
                }
            } catch (Exception e) {
                Log.d("zzd", "regist AOA plugin error!\t" + e.getMessage());
            }
        }
    }
}
